import { Modal, message } from 'antd'
import React, { useRef, useState } from 'react'
import EditableProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { request, FormattedMessage, useT } from '@designable/event-system'

// 选择二级客户
export function agreementCustomer(params: any) {
  return request({
    uri: '/api/tenant/agreement/customer/list',
    params,
    method: 'POST',
  })
}

type SelectModalProps = {
  visible: boolean
  onCancel: () => void
  onOk: (currentData: any) => any
  agreementCode?: string
}

const columns: ProColumns[] = [
  {
    width: 160,
    title: <FormattedMessage id="客户编号" />,
    dataIndex: 'code',
  },
  {
    title: <FormattedMessage id="客户名称" />,
    dataIndex: 'name',
    hideInTable: false,
    render: (_, record) => {
      const { name, pname } = record
      return pname ? `${pname} / ${name}` : name
    },
  },
  {
    width: 150,
    title: <FormattedMessage id="所属国家" />,
    dataIndex: 'countryName',
    ellipsis: true,
    search: false,
  },
  {
    width: 160,
    title: <FormattedMessage id="状态" />,
    dataIndex: 'statusDesc',
    ellipsis: true,
    search: false,
  },
]

export default function CustomersModal(props: SelectModalProps) {
  const { visible, onCancel, onOk, agreementCode } = props
  const actionRef = useRef<ActionType>()

  const [currentData, setCurrentData] = useState<any>({})
  const $t = useT()

  return (
    <Modal
      zIndex={1000}
      title={<FormattedMessage id="客户" />}
      width={1000}
      visible={visible}
      onOk={async () => {
        if (!currentData.id) {
          message.error($t('请选择'))
          return
        }
        onOk(currentData)
      }}
      onCancel={() => {
        onCancel()
      }}
    >
      <EditableProTable
        columns={columns}
        actionRef={actionRef}
        tableAlertRender={false}
        rowSelection={{
          type: 'radio',
          defaultSelectedRowKeys: currentData.id ? [currentData.id] : [],
          onChange: (keys, rows) => {
            setCurrentData(rows[0])
          },
        }}
        request={async (params) => {
          const { pageSize } = params
          const res: any = await agreementCustomer({
            ...params,
            size: pageSize,
            agreementCode,
          })
          return {
            data: res,
            success: true,
            total: res.length,
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          collapsed: false,
          collapseRender: () => <></>,
        }}
        pagination={{
          size: 'default',
          defaultPageSize: 10,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100'],
        }}
        dateFormatter="string"
        toolBarRender={false}
      />
    </Modal>
  )
}
